<template>
  <div />
</template>

<script>
import { mapGetters } from 'vuex'
import { getAccessToken, getUserInfo, scanLogin } from '@/api/user'
import { selectAllList } from '@/api/common'

export default {
  name: 'WxBind',
  data() {
    return {
      code: this.$route.query.code || '1',
      state: this.$route.query.state || '',
      wxUserInfo: {},
      toRouter: '',
      fromRouter: ''
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  watch: {
    $route: {
      handler: function(to, from) {
        console.log(to, from)
      },
      immediate: true
    }
  },
  // // 在路由改变之前
  beforeRouteEnter(to, from, next) {
    // console.log(to, from, next, 'to, from, next')
    if (
      from.path === '/password' ||
      from.path === '/mobileLogin' ||
      from.path === '/register'
    ) {
      next((vm) => {
        vm.login()
      })
    } else {
      next((vm) => {
        vm.getWxUserInfo()
      })
    }
  },
  created() {},
  mounted() {},
  methods: {
    async login() {
      const { data } = await getAccessToken({
        code: this.$route.query.code || '0219Dbkc050TCz1hoVhc0nGpkc09DbkZ'
      })
      const { accessToken, openId } = data
      const userInfo = await getUserInfo({
        openId: openId,
        accessToken: accessToken
      })
      this.$store.dispatch('user/setwxUserInfo', userInfo.data)
      localStorage.setItem('wxUserInfo', JSON.stringify(userInfo.data))
      const res = await scanLogin({
        unionId: userInfo.data.unionId,
        thirdAppId: userInfo.data.thirdAppId,
        openId: userInfo.data.openId,
        bindType: userInfo.data.bindType
      })
      await this.$store.dispatch('user/login', res.data)
      const busiesList = await selectAllList()
      if (res.data.auditStatus === 2) {
        await this.$store.dispatch('user/changeRoles', busiesList.data[0])
        this.$router.push('/home')
      } else {
        this.$router.push('/register')
      }
      console.log(userInfo, 'userInfo')
      this.$router.go(-1)
    },
    getWxCode() {
      this.$store.dispatch(
        'user/setwxCode',
        this.code || '071R1P3b2PJdFL03Wr4b20874b2R1P3K'
      )
    },
    async getWxUserInfo() {
      const { data } = await getAccessToken({
        code: this.$route.query.code || '0716uI1M1bdHpa1KlE1M14ru1M16uI1u'
      }).catch(() => {
        this.$message({
          message: '请重新扫码',
          type: 'error'
        })
        this.$router.go(-1)
      })

      const { accessToken, openId } = data
      const userInfo = await getUserInfo({
        openId: openId,
        accessToken: accessToken
      })
      this.$store.dispatch('user/setwxUserInfo', userInfo.data)
      localStorage.setItem('wxUserInfo', JSON.stringify(userInfo.data))
      this.$router.go(-1)
    }
  }
}
</script>
